package com.hrz.datasync.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class BaseController {
    /**
     *
     * 功能描述:
     * MD5加密处理
     * @参  数:
     * @返  回:
     * @作  者: 侯建军
     * @日  期: 2018/11/06 04:36:48
     */
    public String MD5(String str) {
        if (StringUtils.isNotBlank(str)) {
            return DigestUtils.md5DigestAsHex(str.getBytes());
        }
        return null;
    }

    /**
     * 获取参数
     * @param request
     * @return
     */
    public Map<String, Object> getParams(HttpServletRequest request) {
        Map<String, Object> paramMap = new HashMap<>();
        Map<String, String[]> params = request.getParameterMap();
        Set<Map.Entry<String, String[]>> set = params.entrySet();
        Iterator<Map.Entry<String, String[]>> it = set.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String[]> entry = it.next();
            String key 		= entry.getKey();
            String values[] = entry.getValue();
            // 剔除PageUtil里的参数
            if (!key.equals("page") && !key.equals("rows") && !key.equals("totalPage") && !key.equals("totalRow") && !key.equals("sort") && !key.equals("order") && !key.equals("params")) {
                if (values.length > 0) {
                    if (key.contains("[]")) {// 数组
                        key = key.replace("[]", "");
                        paramMap.put(key, values);
                    } else {
                        if (values.length == 1) {
                            paramMap.put(key, values[0]);
                        }else{
                            paramMap.put(key, values);
                        }
                    }
                }
            }
        }
        return paramMap;
    }
    /**
     *
     * 功能描述:
     * 错误信息显示
     * @参  数:
     * @返  回:
     * @作  者: 侯建军
     * @日  期: 2018/11/06 04:36:18
     */
    public String getErrors(Exception e){
        StringBuilder errors = new StringBuilder();
        StackTraceElement[] stes = e.getStackTrace();
        for (StackTraceElement ste : stes) {
            errors.append(ste.getClassName());
            errors.append("\n");
        }
        return errors.toString();
    }
    /**
     *
     * 功能描述:
     * 设置头信息
     * @参  数:
     * @返  回:
     * @作  者: 侯建军
     * @日  期: 2018/11/06 04:36:04
     */
    public void setHeader(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods","POST");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");
        response.setHeader("refresh","1");
    }
}
